<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '地图选点报修',
  },
}
</route>

<template>
  <view class="map-container">
    <!-- 地图组件 -->
    <web-view class="map-view" :src="mapUrl"></web-view>

    <!-- 设施分类选择 -->
    <view class="category-filter">
      <scroll-view scroll-x class="category-scroll">
        <view class="category-list">
          <view
            v-for="item in categories"
            :key="item.id"
            :class="['category-item', selectedCategory === item.id ? 'active' : '']"
            @click="handleCategorySelect(item)"
          >
            {{ item.name }}
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 设施列表 -->
    <view class="facility-list" v-if="role === 1">
      <view
        v-for="item in filteredFacilities"
        :key="item.id"
        class="facility-item"
        @click="handleFacilitySelect(item)"
      >
        <view class="facility-info">
          <text class="facility-name">{{ item.name }}</text>
          <text class="facility-address">{{ item.address }}</text>
        </view>
        <view class="facility-status">
          <wd-tag :type="item.status === 1 ? 'success' : item.status === 2 ? 'warning' : 'danger'">
            {{ item.status === 1 ? '正常' : item.status === 2 ? '维修中' : '故障待修' }}
          </wd-tag>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { getFacilityCategories, getFacilityList } from '@/service/map'
import { useUserStore } from '@/store'

interface Category {
  id: number
  name: string
  deptId: number
}

interface Facility {
  id: number
  name: string
  categoryId: number
  address: string
  longitude: number
  latitude: number
  status: 1 | 2 // 1正常，2维修中
}

interface CategoryResponse {
  data: {
    records: Category[]
    total: number
    size: number
    current: number
    pages: number
  }
}

interface FacilityResponse {
  data: Facility[]
}

const userStore = useUserStore()
const role = userStore.role
// 地图URL
const getMapUrl = (facilities: Facility[]) => {
  // 基础URL
  const baseUrl = 'https://m.amap.com/navi/'

  // 构建参数
  const params = new URLSearchParams({
    dest: '110.738261,32.650783', // 学校中心点
    destName: '湖北汽车工业学院',
    hideRouteIcon: '1',
    key: '7687a541785330a129a557fe784b1c65',
    jscode: '4e287afc97ed94523aa3eaf10a800ddd',
  })

  // 添加设施标记点
  facilities.forEach((facility, index) => {
    params.append(`markers[${index}]`, `${facility.longitude},${facility.latitude}`)
    params.append(`name[${index}]`, facility.name)
  })

  return `${baseUrl}?${params.toString()}`
}

const mapUrl = ref('')

// 所有的分类
const categories = ref<Category[]>([])
// 选中的分类id
const selectedCategory = ref<number | null>(null)

// 设施列表数据
const facilities = ref<Facility[]>([])

// 根据分类筛选设施
const filteredFacilities = computed(() => {
  if (!selectedCategory.value) return facilities.value
  return facilities.value.filter((item) => item.categoryId === selectedCategory.value)
})

// 获取设施分类
const loadCategories = async () => {
  try {
    const res = (await getFacilityCategories({ current: 1, size: 50 })) as CategoryResponse
    categories.value = res.data.records
  } catch (error) {
    console.error('获取设施分类失败:', error)
    categories.value = []
  }
}

// 获取设施列表
const loadFacilities = async () => {
  try {
    const res = (await getFacilityList()) as FacilityResponse
    facilities.value = res.data
    // 更新地图URL，添加设施标记点
    mapUrl.value = getMapUrl(facilities.value)
  } catch (error) {
    console.error('获取设施列表失败:', error)
    facilities.value = []
  }
}

// 选择分类
const handleCategorySelect = (category: Category) => {
  // 如果点击的是当前选中的分类，取消选中（返回全部设施）
  // 如果点击的是其他分类，选中该分类
  selectedCategory.value = selectedCategory.value === category.id ? null : category.id

  // 根据筛选结果更新地图标记点
  const filteredFacs = selectedCategory.value
    ? facilities.value.filter((item) => item.categoryId === selectedCategory.value)
    : facilities.value
  mapUrl.value = getMapUrl(filteredFacs)
}

// 选择设施
const handleFacilitySelect = (facility: Facility) => {
  if (facility.status !== 1) {
    uni.showToast({
      title: facility.status === 2 ? '该设施正在维修中' : '该设施故障待修',
      icon: 'none',
    })
    return
  }

  // 跳转到报修页面,传递设施信息
  uni.navigateTo({
    url: `/pages/submit/index?facilityId=${facility.id}&facilityName=${facility.name}&facilityAddress=${facility.address}`,
  })
}

// 页面加载时获取数据
onLoad(() => {
  loadCategories()
  loadFacilities()
})
</script>

<style lang="scss" scoped>
.map-container {
  position: relative;
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.map-view {
  flex: 1;
  width: 100%;
}
.main-body {
  :deep(.poi-card) {
    display: none !important;
  }
}

.category-filter {
  position: fixed;
  right: 0;
  left: 0;
  z-index: 100;
  padding: 12px 0;
  background-color: rgba(255, 255, 255, 0.95);
}

.category-scroll {
  padding: 0 12px;
  white-space: nowrap;
}

.category-list {
  display: inline-flex;
  gap: 8px;
}

.category-item {
  padding: 6px 12px;
  font-size: 14px;
  color: #666;
  background-color: #f5f5f5;
  border-radius: 16px;

  &.active {
    color: #fff;
    background-color: #1989fa;
  }
}

.facility-list {
  position: fixed;
  right: 0;
  bottom: 0vh;
  left: 0;
  z-index: 999;
  height: 35%;
  padding: 16px;
  overflow-y: auto;
  background-color: #fff;
  border-radius: 20px 20px 0 0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.facility-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  border-bottom: 1px solid #f5f5f5;

  &:last-child {
    border-bottom: none;
  }
}

.facility-info {
  flex: 1;
}

.facility-name {
  display: block;
  margin-bottom: 4px;
  font-size: 16px;
  color: #333;
}

.facility-address {
  font-size: 12px;
  color: #999;
}
</style>
